package com.ruoyi.auth.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.WxMaUserService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.ruoyi.auth.service.WxUserService;
import com.ruoyi.common.core.constant.CacheConstants;
import com.ruoyi.common.core.constant.TokenConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.JwtUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.customer.api.domain.AuthPhone;
import com.ruoyi.customer.api.domain.WxLoginBody;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
public class WxUserController {

    @Autowired
    private WxMaService wxMaService;
    @Autowired
    WxUserService wxUserService;
    @Autowired
    RedisService redisService;

    @RequestMapping("/wxLogin")
    public R<?> login(@RequestBody WxLoginBody wxLoginBody) {
        WxMaUserService userService = wxMaService.getUserService();
        try {
            WxMaJscode2SessionResult sessionInfo = userService.getSessionInfo(wxLoginBody.getCode());
            Map<String, Object> stringObjectMap = wxUserService.wxLogin(sessionInfo, wxLoginBody);
            return R.ok(stringObjectMap);
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
    }


    @PostMapping("/authPhone")
    @ApiOperation("授权获取用户手机号")
    public R<?> authPhone(@RequestBody AuthPhone param) throws Exception {
        String s = wxUserService.authPhone(param);
        return StringUtils.isNotEmpty(s) ? R.ok(s, "操作成功") : R.fail();
    }

    @GetMapping("/checkToken")
    public R<Boolean> checkToken(@RequestHeader(value =TokenConstants.AUTHENTICATION, required = false) String token) {
        // 如果前端设置了令牌前缀，则裁剪掉前缀
        if (StringUtils.isNotEmpty(token) && token.startsWith(TokenConstants.PREFIX)) {
            token = token.replaceFirst(TokenConstants.PREFIX, StringUtils.EMPTY);
        } else {
            return R.ok(false);
        }
        Claims claims = JwtUtils.parseToken(token);
        if (claims == null) {
            return R.ok(false);
        }
        String userkey = JwtUtils.getUserKey(claims);
        boolean islogin = redisService.hasKey(getTokenKey(userkey));
        if (!islogin) {
            return R.ok(false);
        }
        return R.ok(true);
    }

    private String getTokenKey(String token) {
        return CacheConstants.LOGIN_TOKEN_KEY + token;
    }
}
